package com.yanqu.road.server.logic.thread;

import com.yanqu.road.logic.redis.RedisForbiddenWords;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ForbiddenWordMgr;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.http.HttpHelper;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

public class ForbiddenWordTask extends GeneralTask {
    private Logger logger = LogManager.getLogger(ForbiddenWordTask.class.getName());

    public ForbiddenWordTask() {
        super();
    }

    @Override
    public void doRun() {
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("time", (System.currentTimeMillis() / 1000) + "");
        String sign = SignHelper.getSign(paramMap, AppKeyMgr.getAndroidAppSecret());
        paramMap.put("sign", sign);
        try {
            String url = AppKeyMgr.getPlatformBaseUrl() + "/chat/getWord/" + AppKeyMgr.getAndroidAppId() + "/" + AppKeyMgr.getPlatformChannelId();
            logger.info("ForbiddenWord url:{}", url);
            Map<String, String> resultMap = HttpHelper.doGet(url, paramMap);
            if(null != resultMap && "200".equals(resultMap.get("code"))){
                logger.info("ForbiddenWord code:{}", resultMap.get("code"));
                String body = resultMap.get("body");
                String[] wordListStr = body.split("\n");
                List<String> words = new ArrayList<>();
                for (String wordStr : wordListStr) {
                    words.add(wordStr.split("\\|\\|")[0]);
                }
                //将获得的敏感词加入redis中
                RedisForbiddenWords.setWords(AppKeyMgr.getAndroidAppId(), AppKeyMgr.getPlatformChannelId(), words);
                ForbiddenWordMgr.addForbiddenWord(words);

            }else {
                logger.info("ForbiddenWord request error");
            }
        } catch (Exception e) {
            logger.error("ForbiddenWord error:",e);
        }
    }
}
